import numpy as np
# 乘法层
class MultiLayer:
    def __init__(self):
        self.x = None
        self.y = None

    def forward(self, x,y):
        self.x = x
        self.y = y
        out = x * y
        return out

    def backward(self, dout):
        dx = dout * self.y
        dy = dout * self.x
        return dx, dy

# 加法层
class AddLayer:
    def __init__(self):
        pass

    def forward(self, x, y):
        out = x + y
        return out

    def backward(self, dout):
        dx = dout * 1
        dy = dout * 1
        return dx, dy

class Relu:
    def __init__(self):
        # 这个变量mask是由True/False构成的NumPy数组
        self.mask = None

    def forward(self, x):
        self.mask = (x <= 0)
        out = x.copy()
        out[self.mask] = 0

        return out

    def backward(self, dout):
        dx = dout * (self.mask == False)
        return dx


class Sigmoid:
    def __init__(self):
        self.out = None
    def forward(self, x):
        out = 1 / (1 + np.exp(-x))
        self.out = out
        return out
    def backward(self,dout):
        dx = dout * (self.out * (1.0 - self.out))
        return dx



if __name__ == '__main__':
    apple  = 100
    apple_num = 2
    orange = 150
    orange_num = 3
    tax = 1.1
     # layer
    mul_apple_layer = MultiLayer()
    mul_orange_layer = MultiLayer()
    add_apple_orange_layer = AddLayer()
    mul_tax_layer = MultiLayer()

    # forward
    apple_price = mul_apple_layer.forward(apple, apple_num)
    orange_price = mul_orange_layer.forward(orange, orange_num)
    apple_orange_price = add_apple_orange_layer.forward(apple_price, orange_price)
    price = mul_tax_layer.forward(apple_orange_price, tax)

    print(f"apple_price: {apple_price}")

    #backward
    dprice = 1
    dall_price, dtax = mul_tax_layer.backward(dprice)
    dapple_price, dorange_price = add_apple_orange_layer.backward(dall_price)
    dapple, dapple_num = mul_apple_layer.backward(dapple_price)
    dorange_price, dorange_num = mul_orange_layer.backward(dorange_price)
    print(f"dapple: {dapple}")
    print(f"dapple_num: {dapple_num}")
    print(f"dorange: {dorange_price}")
    print(f"dorange_num: {dorange_num}")
    print(f"dtax: {dtax}")

